﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;
using System.Windows;
using System.Collections.Specialized;
namespace GoldenWOWLauncher.Functions
{
    public class LocalServices
    {
        public delegate void AfterRequest<T>(T Result);

        public class Web连接 
        {
          
            public string? Url { get; set; }

            public BackgroundWorker Execute(string QueryString, string Data, AfterRequest<int> afterRequest, AfterRequest<Exception> afterError)
            {
                string? url = Url + @"/" + QueryString;
                if (!string.IsNullOrEmpty(url))
                    return LocalServices.AsyncAPI.Request(LocalServices.AsyncAPI.RequestType.Get, url, Data,
                           (string result) =>
                           {
                               try
                               {
                            
                                   if (!string.IsNullOrEmpty(result))
                                   {
                                       object? Result = null;
                                       try
                                       {
                                           Dictionary<string, string> rez = LocalServices.JsonToDictionary(result);
                                           if (!rez.ContainsKey("Code") || !rez.ContainsKey("Result") || !rez.ContainsKey("Data"))
                                           {
                                               throw new Exception("服务器反馈信息异常。");
                                           }
                                           afterRequest(LocalServices.ToInt(rez["Code"]));
                                       }
                                       catch (Exception ex)
                                       {
                                           afterError.Invoke(ex);
                                       }
                                     
                                   }

                                   afterError.Invoke(new Exception("服务器无反馈。"));

                               }
                               catch (Exception ex)
                               {
                                   afterError.Invoke(ex);
                               }

                           }
                            ,
                           (Exception ex) =>
                           {
                               afterError.Invoke(ex);
                           });

                throw new Exception("No Url setted");
            }

            public BackgroundWorker FetchObject(string QueryString, string Data, AfterRequest<object?> afterRequest, AfterRequest<Exception> afterError)
            {
                string? url = Url + @"/" + QueryString;
                if (!string.IsNullOrEmpty(url))
                    return LocalServices.AsyncAPI.Request(LocalServices.AsyncAPI.RequestType.Get, url, Data,
                                                (string result) =>
                                                {
                                                    if (!string.IsNullOrEmpty(result))
                                                    {
                                                        object? Result = null;
                                                        try
                                                        {
                                                            Dictionary<string, string> rez = LocalServices.JsonToDictionary(result);
                                                            if (!rez.ContainsKey("Code") || !rez.ContainsKey("Result") || !rez.ContainsKey("Data"))
                                                            {
                                                                throw new Exception("服务器反馈信息异常。");
                                                            }
                                                            if (rez["Code"] != "0")
                                                            {
                                                                throw new Exception("访问失败：" + rez["Result"]);
                                                            }

                                                            Result = rez["Data"];
                                                            afterRequest(Result);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            afterError.Invoke(ex);
                                                        }

                                                    }

                                                    afterError.Invoke(new Exception("服务器无反馈。"));
                                                }
                                                ,
                                                (Exception ex) =>
                                                {
                                                    afterError.Invoke(ex);
                                                });
                throw new Exception("No Url setted");
            }

            public BackgroundWorker FetchList(string QueryString, string Data, AfterRequest<List<string>?> afterRequest, AfterRequest<KeyValuePair<string, Exception>> afterError)
            {
                string? url = Url + @"/" + QueryString;
                if (!string.IsNullOrEmpty(url))
                    return LocalServices.AsyncAPI.Request(LocalServices.AsyncAPI.RequestType.Get, url, Data,
                                                (string result) =>
                                                {
                                                    List<string>? Result = null;
                                                    try
                                                    {
                                                        Dictionary<string, string> rez = LocalServices.JsonToDictionary(result);
                                                        if (!rez.ContainsKey("Code") || !rez.ContainsKey("Result") || !rez.ContainsKey("Data"))
                                                        {
                                                            throw new Exception("服务器反馈信息异常。");
                                                        }
                                                        if (rez["Code"] != "0")
                                                        {
                                                            throw new Exception("访问失败：" + rez["Result"]);
                                                        }

                                                        Result = LocalServices.JsonToList(rez["Data"]);
                                                        afterRequest(Result);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        afterError.Invoke(new KeyValuePair<string, Exception>($"FetchList:GotResult:{QueryString}:{Data}", ex));
                                                    }
                                                    //afterRequest(Result);
                                                }
                                                ,
                                                (Exception ex) =>
                                                {
                                                    afterError.Invoke(new KeyValuePair<string, Exception>($"FetchList:FailedGotResult:{QueryString}:{Data}", ex));
                                                });
                else
                    throw new Exception("No Url setted");
            }

            public BackgroundWorker FetchDictionary(string QueryString, string Data, AfterRequest<Dictionary<string,string>?> afterRequest, AfterRequest<Exception> afterError)
            {
                string? url = Url + @"/" + QueryString;
                if (!string.IsNullOrEmpty(url))
                    return LocalServices.AsyncAPI.Request(LocalServices.AsyncAPI.RequestType.Get, url, Data,
                                                (string result) =>
                                                {
                                                    Dictionary<string, string>? Result = null;
                                                    try
                                                    {
                                                        Dictionary<string, string> rez = LocalServices.JsonToDictionary(result);
                                                        if (!rez.ContainsKey("Code") || !rez.ContainsKey("Result") || !rez.ContainsKey("Data"))
                                                        {
                                                            throw new Exception("服务器反馈信息异常。");
                                                        }
                                                        if (rez["Code"] != "0")
                                                        {
                                                            throw new Exception("访问失败：" + rez["Result"]);
                                                        }

                                                        Result = LocalServices.JsonToDictionary(rez["Data"]);
                                                        afterRequest(Result);
                                                    }
                                                    catch (Exception ex)
                                                    {
                                                        afterError.Invoke(ex);
                                                    }
                                                    afterRequest(Result);

                                                }
                                                ,
                                                (Exception ex) =>
                                                {
                                                    afterError.Invoke(ex);
                                                });
                throw new Exception("No Url setted");
            }



   
        }

   

        /// <summary>
        /// 异步
        /// </summary>
        public class AsyncAPI
        {
            public enum RequestType
            {
                Post,
                Get,
                Put,
                Delete
            }

            public static BackgroundWorker Request(RequestType requestType, string url, string data, AfterRequest<string> AfterPost, AfterRequest<Exception> ErrorPost)
            {
                BackgroundWorker bw = new BackgroundWorker();
                try
                {
                    Task<WebResponse> tResult = AsyncAPI.RequestAsync(requestType, url, data);
                    //tResult.Start();
                    bw.DoWork += (sender, e) =>
                    {
                        #region 等待时期
                        while (!tResult.IsCompleted && !tResult.IsCompletedSuccessfully && !tResult.IsCanceled && !tResult.IsFaulted)
                        {
                            Thread.Sleep(0);
                            #region 终止机制
                            if (bw.CancellationPending)
                            {
                                Exception? exception = new Exception();
                                try
                                {
                                    tResult.Dispose();
                                }
                                catch (Exception exx)
                                {
                                    exception = exx;
                                }
                                e.Result = new Exception("取消", exception);
                                return;
                            }
                            #endregion
                        }
                        #endregion

                        if (tResult.IsCompleted || tResult.IsCompletedSuccessfully)
                        {
                            using (HttpWebResponse _response = (HttpWebResponse)tResult.Result)
                            {
                                StreamReader reader = new StreamReader(_response.GetResponseStream());

                                #region 最后一步用异步处理
                                Task<string> tResult2 = reader.ReadToEndAsync();

                                #region 等待时期
                                while (!tResult2.IsCompleted && !tResult2.IsCompletedSuccessfully && !tResult2.IsCanceled && !tResult2.IsFaulted)
                                {
                                    Thread.Sleep(0);

                                    #region 终止机制
                                    if (bw.CancellationPending)
                                    {
                                        Exception? exception = new Exception();
                                        try
                                        {
                                            tResult2.Dispose();
                                        }
                                        catch (Exception exx)
                                        {
                                            exception = exx;
                                        }
                                        e.Result = new Exception("取消", exception);
                                        return;
                                    }
                                    #endregion
                                }
                                #endregion

                                #endregion

                                if (tResult2.IsCompleted || tResult2.IsCompletedSuccessfully)
                                {
                                    e.Result = tResult2.Result;
                                    return;
                                }
                                else
                                {
                                    e.Result = tResult2.Exception;
                                    return;
                                }
                            }

                        }
                        else
                        {
                            e.Result = tResult.Exception;
                            return;
                        }
                    };
                    bw.RunWorkerCompleted += (sender, e) =>
                    {
                        if (e != null)
                        {
                            if (e.Result != null && LocalServices.源头一致吗(e.Result.GetType(), typeof(Exception)))
                            {
                                #region 说明操作失败
                                ErrorPost(e.Result as Exception);
                                #endregion
                            }

                            try
                            {
                                AfterPost(LocalServices.ToString(e.Result));
                            }
                            catch (Exception ex)
                            {
                                ErrorPost(ex);
                            }
                        }
                    };
                    bw.RunWorkerAsync();
                }
                catch (Exception ex)
                {
                    ErrorPost(ex);
                }
                return bw;
            }

            /// <summary>
            /// 发送请求并异步处理返回
            /// </summary>
            /// <param name="url"></param>
            /// <param name="data"></param>
            /// <returns></returns>
            private static Task<WebResponse> RequestAsync(RequestType rtype, string url, string data)
            {
                Task<WebResponse> Result = null;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (request == null)
                    return Result;
                request.ServerCertificateValidationCallback = (_s, _x509s, _x509c, _ssl) => { return (true); };
                switch (rtype)
                {
                    case RequestType.Post:
                        {
                            request.Method = "POST";
                            request.ContentType = "application/json";
                            byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
                            request.ContentLength = byteData.Length;
                            using (Stream postStream = request.GetRequestStream())
                            {
                                postStream.Write(byteData, 0, byteData.Length);
                            }
                        }
                        break;
                    case RequestType.Get:
                        request.Method = "GET";
                        request.ContentType = "application/json;charset=UTF-8";
                        //request.ContentType = "text/plain;charset=UTF-8";
                        //request.UserAgent = constan
                        break;
                    case RequestType.Put:
                        request.Method = "PUT";
                        request.ContentType = "application/json";
                        break;
                    case RequestType.Delete:
                        request.Method = "DELETE";
                        request.ContentType = "application/json";
                        break;
                }

                Result = request.GetResponseAsync();
                return Result;
            }

        }



        /// <summary>
        /// 看某个东西时候是空的
        /// </summary>
        /// <param name="something"></param>
        /// <returns></returns>
        private static bool IsEmpty(object? something)
        {
            bool result = true;

            if (something == null)
                return result;

            if (something == DBNull.Value)
                return result;

            if (string.IsNullOrEmpty(something.ToString()))
                return result;

            return !result;
        }

        /// <summary>
        /// 安全转化为字符串
        /// </summary>
        /// <param name="something"></param>
        /// <returns></returns>
        public static string ToString(object? something)
        {
            if (IsEmpty(something))
                return string.Empty;
            return something.ToString();
        }

        /// <summary>
        /// 1万以内中文转数字
        /// </summary>
        /// <param name="src">源文本如：四千三百二十一</param>
        /// <returns></returns>
        private static int Convert2Number(string src)
        {
            // 定义包含所有数字的字符串，用以判断字符是否为数字。
            string numberString = "零一二三四五六七八九";
            // 定义单位字符串，用以判断字符是否为单位。
            string unitString = "零十百千";
            // 把数字字符串转换为char数组，方便截取。
            char[] charArr = src.Replace(" ", "").ToCharArray();
            // 返回结果
            int result = 0;
            // 如果源为空指针、空字符串、空白字符串 则返回0
            if (string.IsNullOrEmpty(src) || string.IsNullOrWhiteSpace(src))
            {
                return 0;
            }
            // 如果源的第一个字符不是数字 则返回0
            if (numberString.IndexOf(charArr[0]) == -1)
            {
                return 0;
            }
            // 遍历字符数组
            for (int i = 0; i < charArr.Length; i++)
            {
                // 遍历单位字符串
                for (int j = 0; j < unitString.Length; j++)
                {
                    // 如果字符为单位则进行计算
                    if (charArr[i] == unitString[j])
                    {
                        // 如果字符为非'零'字符，则计算出十位以上到万位以下数字的和
                        if (charArr[i] != '零')
                        {
                            result += Convert.ToInt32(int.Parse(numberString.IndexOf(charArr[i - 1]).ToString()) * Math.Pow(10, j));
                        }
                    }
                }
            }
            // 如果源文本末尾字符为'零'-'九'其中之一，则计算结果和个位数相加。
            if (numberString.IndexOf(charArr[charArr.Length - 1]) != -1)
            {
                result += numberString.IndexOf(charArr[charArr.Length - 1]);
            }
            // 返回计算结果。
            return result;
        }
        /// <summary>
        /// 中文转数字
        /// </summary>
        /// <param name="src">中文数字 如：九亿八千七百六十五万四千三百二十一</param>
        /// <returns></returns>
        private static string Chinese2Num(string src)
        {
            // 定义一个数组，用于接受分割字符串的结果
            string[] srcArr;
            // 定义计算结果
            int result = -1;
            // 如果字符串中包含'亿'则进行分割
            if (src.IndexOf("亿") != -1)
            {
                // 以字符'亿'分割源字符串
                srcArr = src.Split('亿');
                // 计算亿以上的数字
                result += Convert.ToInt32(Convert2Number(srcArr[0]) * Math.Pow(10, 8));
                // 如果剩余字符串中包括'万'，则再次进行分割
                if (src.IndexOf("万") != -1)
                {
                    // 以字符'万'分割源字符串
                    srcArr = srcArr[1].Split('万');
                    // 计算万以上亿以下的数字
                    result += Convert.ToInt32(Convert2Number(srcArr[0]) * Math.Pow(10, 4)) + Convert.ToInt32(Convert2Number(srcArr[1]));
                }
            }
            // 如果字符串中不包含字符'亿'
            else
            {
                // 如果源字符串中包括'万'，则以'万'字进行分割
                if (src.IndexOf("万") != -1)
                {
                    srcArr = src.Split('万');
                    result += Convert.ToInt32(Convert2Number(srcArr[0]) * Math.Pow(10, 4)) + Convert.ToInt32(Convert2Number(srcArr[1]));
                }
                else
                {
                    // 源文本为1万以下的数字
                    result += Convert.ToInt32(Convert2Number(src));
                }
            }
            if (result > 0)
            {
                result++;
                return result.ToString();
            }
            return src;
        }

        /// <summary>
        /// 全角转半角
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private static String ToDBC(String input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new String(c);
        }

        /// <summary>
        /// 字符串转整形，核心在“Tools.字符串转浮点()”处。不会因为转换类型而报错，顶多是转换成大段字符提取不了数字，返回为0
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>整形</returns>
        private static int StringToInt(string str)
        {
            int result = 0; ;
            if (string.IsNullOrEmpty(str))
                return 0;
            switch (str.Trim().ToLower())
            {
                case "true":
                case "t":
                    return 0;
            }
            string newStr = string.Empty;
            newStr = Chinese2Num(str).ToString();
            newStr = str.Trim("0123456789.+-".ToCharArray());
            str = str.Trim(newStr.ToCharArray());
            if (!int.TryParse(str, out result))
            {
                string NewStr = ToDBC(str);
                if (NewStr != str)
                    return StringToInt(NewStr);
                result = 0;
            }
            return result;
        }

        /// <summary>
        /// 万物转整形，核心在“Tools.字符串转浮点()”处。不会因为转换类型而报错，顶多是转换成大段字符提取不了数字，返回为0
        /// </summary>
        /// <param name="obj">任何类型</param>
        /// <returns>整形</returns>
        public static int ToInt(object? anything)
        {
            if (anything == null)
                return 0;
            if (anything == DBNull.Value)
                return 0;
            return StringToInt(anything.ToString());
        }
        public static bool 源头一致吗(Type anytype, Type type)
        {
            if (anytype == null)
                return false;
            if (anytype == type)
                return true;
            return 源头一致吗(anytype.BaseType, type);
        }

        /// <summary>
        /// 增加引号
        /// </summary>
        /// <param name="msg">内容</param>
        /// <param name="toquote">引号</param>
        /// <returns>增加好引号的内容</returns>
        private static string 加引号(string msg, string toquote)
        {
            string result = string.Empty;
            result = toquote + msg + toquote;
            return result;
        }

        /// <summary>
        /// 增加引号
        /// </summary>
        /// <param name="msg">内容</param>
        /// <param name="front">起始端引号</param>
        /// <param name="end">末端引号</param>
        /// <returns>增加好引号的内容</returns>
        private static string 加引号(string msg, string front, string end)
        {
            return front + msg + end;
        }

        /// <summary>
        /// 获取引号内的内容。“末尾引号”参数可选，如果不填写，那就默认使用“引号”参数作为末尾引号
        /// </summary>
        /// <param name="Msg">内容</param>
        /// <param name="Quote">引号</param>
        /// <param name="QuoteLast">末尾引号</param>
        /// <returns>带引号的字符串</returns>
        private static string 读引用(string msg, string quote, string quotelast = "", bool 最内层括号 = false, bool ToLower = false)
        {
            string Msg = msg;
            string Quote = quote;
            string QuoteLast = quotelast;
            if (ToLower)
            {
                Msg = msg.ToLower();
                Quote = quote.ToLower();
                QuoteLast = quotelast.ToLower();
            }
            string substring = string.Empty;
            if (!最内层括号)
            {
                if (QuoteLast == "") QuoteLast = Quote;
                if (!Msg.Contains(Quote) || !Msg.Contains(QuoteLast))
                    return Msg;
                if (Msg.IndexOf(Quote) == Msg.Length - 1)
                    return string.Empty;
                int times = 0;
                for (int i = Msg.IndexOf(Quote) + Quote.Length; i < Msg.Length; i++)
                {
                    int j = i;
                    if ((i + QuoteLast.Length < Msg.Length) && (i + Quote.Length < Msg.Length))
                    {
                        if (Quote != QuoteLast)
                        {
                            if (times == 0 && Msg.Substring(i, Quote.Length) != Quote && Msg.Substring(i, QuoteLast.Length) == QuoteLast)
                                return substring;
                            if ((i + Quote.Length <= Msg.Length) && (Msg.Substring(i, Quote.Length) == Quote))
                            {
                                times++;
                                j += (Quote.Length > 1) ? Quote.Length - 1 : 0;
                            }
                            else if (Msg.Substring(i, QuoteLast.Length) == QuoteLast)
                            {
                                times--;
                                j += (Quote.Length > 1) ? Quote.Length - 1 : 0;
                                if (times < 0)
                                    times = 0;
                            }
                        }
                        else
                        {
                            if (times == 0 && Msg.Substring(i, QuoteLast.Length) == QuoteLast)
                            {
                                times++;
                            }
                            if (times > 0 && Msg.Substring(i, QuoteLast.Length) == QuoteLast)
                                return substring;

                        }

                    }
                    else if ((i + Quote.Length == Msg.Length) || (i + QuoteLast.Length == Msg.Length))
                    {
                        return substring;
                    }

                    int nextIndex = (j - i) > 0 ? (j - i) : 1;
                    substring += msg.Substring(i, nextIndex);
                    i = j;
                }

                return substring;
                //if (Msg.IndexOf(Quote) != Msg.LastIndexOf(QuoteLast))
                //    substring = Msg.Substring(Msg.IndexOf(Quote) + Quote.Length, Msg.LastIndexOf(QuoteLast) - Msg.IndexOf(Quote) - Quote.Length);
                //else
                //    substring = Msg.Substring(Msg.IndexOf(Quote) + Quote.Length, Msg.Length - Msg.IndexOf(Quote) - Quote.Length);
                //return substring;
            }
            int first = -1;
            int last = -1;
            for (int i = 0; i < Msg.Length; i++)
            {
                if (last == -1)
                {
                    if (Msg.Length > i + Quote.Length && Msg.Substring(i, Quote.Length) == Quote)
                    {
                        first = i;
                    }
                    else if (first > -1 && Msg.Length >= i + QuoteLast.Length && Msg.Substring(i, QuoteLast.Length) == QuoteLast)
                    {
                        last = i;
                    }
                }
            }
            if (first > -1 && last == -1)
            {
                last = Msg.Length;
            }
            if (first > -1 && last > -1 && last > first && Msg.Length > last)
            {
                substring = msg.Substring(first + Quote.Length, last - first - Quote.Length);
            }
            return substring;
        }

        /// <summary>
        /// 替换字符串中的字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="tobeReplaced">待替换字符串</param>
        /// <param name="ReplaceWith">用于替换的字符串</param>
        /// <param name="toLower">是否统一转为小写再比对</param>
        /// <returns>替换后的字符串</returns>
        private static string 替换(string str, string tobeReplaced, string ReplaceWith, bool toLower = false)
        {
            if (toLower)
            {
                str = str.ToLower();
                tobeReplaced = tobeReplaced.ToLower();
            }
            string result = string.Empty;
            for (int i = 0; i < str.Length; i++)
            {
                int length = 0;
                if (i + tobeReplaced.Length < str.Length)
                    length = tobeReplaced.Length;
                else
                    length = str.Length - i;
                if (str.Substring(i, length) != tobeReplaced)
                    result += str.Substring(i, 1);
                else
                {
                    result += ReplaceWith;
                    for (int j = 1; j < tobeReplaced.Length; j++)
                    {
                        i++;
                    }
                    continue;
                }
            }
            return result;

        }

        private static string[] 安全拆分(string Msg, char SplitString, List<KeyValuePair<string, string>> ProtectString = null)
        {
            if ((string.IsNullOrEmpty(Msg)) || (Msg.Length - 1 <= 0))
                return new string[] { Msg };
            string msg = Msg;
            List<string> stringList = new List<string>();
            Dictionary<string, string> ReplacedDict = new Dictionary<string, string>();

            #region 先把包裹起来的替代掉
            int index = 0;
            foreach (KeyValuePair<string, string> protectStr in ProtectString)
            {
                int length = 0;
                do
                {
                    length = msg.Length;
                    string Quoted = 读引用(msg, protectStr.Key, protectStr.Value);
                    if (msg.Length - Quoted.Length >= protectStr.Key.Length + protectStr.Value.Length)
                    {
                        Quoted = protectStr.Key + Quoted + protectStr.Value;
                        string Key = "【替代字符串" + index + "，为了避免重复的可能性我写得特别离谱】";
                        ReplacedDict.Add(Key, Quoted);
                        index++;
                        msg = 替换(msg, Quoted, Key);
                    }

                }
                while (msg.Length != length);

            }
            #endregion

            #region 拆分
            string[] result = msg.Split(SplitString);
            #endregion

            #region 把拆分后的东西还原回来
            for (int i = 0; i < result.Length; i++)
            {
                for (int j = index - 1; j >= 0; j--)
                {
                    string Key = "【替代字符串" + j + "，为了避免重复的可能性我写得特别离谱】";
                    result[i] = 替换(result[i], Key, ReplacedDict[Key]);
                }

            }
            #endregion

            return result;

        }


        /// <summary>
        /// JSON转Dictionary，仅能处理Json类
        /// </summary>
        /// <param name="_Json"></param>
        /// <returns></returns>
        public static Dictionary<string, string> JsonToDictionary(string _Json)
        {
            Dictionary<string, string> EmptyResult = new Dictionary<string, string>();
            EmptyResult.Add("1", _Json);
            if (string.IsNullOrEmpty(_Json))
                return EmptyResult;
            if (LocalServices.加引号(LocalServices.读引用(_Json, "[", "]"), "[", "]") == _Json)
                //throw new Exception("JsonToDictionary方法不能处理Json数组，Json数组需要改用JsonToList方法");
                return EmptyResult;
            //if (Services.加引号(Services.读引用(_Json, "{", "}"), "{", "}") != _Json)
            //    //throw new Exception("JsonToDictionary方法只能处理Json类，其他字符串无法处理");
            //    return EmptyResult;

            Dictionary<string, string> JsonDictionary = new Dictionary<string, string>();

            try
            {
                if (_Json == null)
                    _Json = "";
                if (_Json != "")
                {
                    //if (_Json.Contains("[") && _Json.Contains("]"))
                    //{
                    //    if (_Json.Substring(0, 1) == "[")
                    //    {
                    //        _Json = _Json.Remove(_Json.Length - 1, 1);
                    //        _Json = _Json.Remove(0, 1);
                    //    }
                    //}
                    //if (_Json.Contains("{") && _Json.Contains("}"))
                    {
                        _Json = _Json.Remove(_Json.Length - 1, 1);
                        _Json = _Json.Remove(0, 1);

                        //string[] _S = _Json.Split(',');
                        List<KeyValuePair<string, string>> ProtectString = new List<KeyValuePair<string, string>>();
                        ProtectString.Add(new KeyValuePair<string, string>("[", "]"));
                        ProtectString.Add(new KeyValuePair<string, string>("{", "}"));
                        ProtectString.Add(new KeyValuePair<string, string>("\"", "\""));
                        string[] _S = LocalServices.安全拆分(_Json, ',', ProtectString);
                        foreach (string _D in _S)
                        {
                            //string[] _J = _D.Split(':');
                            string[] _J = LocalServices.安全拆分(_D, ':', ProtectString);
                            string _Key = _J[0].Trim();
                            string _Value = _J[1].Trim();

                            string Quoted = LocalServices.读引用(_Key, "\"", "\"");
                            if ("\"" + Quoted + "\"" == _Key)
                                _Key = Quoted;

                            Quoted = LocalServices.读引用(_Value, "\"", "\"");
                            if ("\"" + Quoted + "\"" == _Value)
                            {
                                _Value = Quoted;
                            }


                            try
                            {
                                JsonDictionary.Add(_Key, _Value);
                            }
                            catch { }
                        }



                    }
                }
            }
            catch
            { }

            return JsonDictionary;
        }

        /// <summary>
        /// Json转List，仅能处理Json数组
        /// </summary>
        /// <param name="_Json"></param>
        /// <returns></returns>
        public static List<string> JsonToList(string _Json)
        {
            List<string> EmptyList = new List<string>();
            EmptyList.Add(_Json);
            if (string.IsNullOrEmpty(_Json))
                return EmptyList;
            if (LocalServices.加引号(LocalServices.读引用(_Json, "{", "}"), "{", "}") == _Json)
                //throw new Exception("JsonToDictionary方法不能处理Json类，Json数组需要改用JsonToList方法");
                return EmptyList;
            if (LocalServices.加引号(LocalServices.读引用(_Json, "[", "]"), "[", "]") != _Json)
                //throw new Exception("JsonToDictionary方法只能处理Json数组，其他字符串无法处理");
                return EmptyList;

            List<string> JsonList = new List<string>();
            _Json = LocalServices.读引用(_Json, "[", "]");
            //string[] Jsons = _Json.Split(',');
            List<KeyValuePair<string, string>> ProtectString = new List<KeyValuePair<string, string>>();
            ProtectString.Add(new KeyValuePair<string, string>("[", "]"));
            ProtectString.Add(new KeyValuePair<string, string>("{", "}"));
            ProtectString.Add(new KeyValuePair<string, string>("\"", "\""));
            string[] Jsons = LocalServices.安全拆分(_Json, ',', ProtectString);
            if (Jsons == null || Jsons.Length == 0)
                JsonList.Add(_Json);
            else
            {
                foreach (string json in Jsons)
                {
                    JsonList.Add(json);
                }
            }
            return JsonList;
        }

        /// <summary>
        /// 字符串转浮点。会尽量提取一般字符串中的数字，忽略非数字字符；布尔描述的true或者t会转化成1，其他字符串会转化成0。
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>浮点</returns>
        private static decimal StringToDecimal(string str)
        {
            decimal result = 0.0M;
            if (string.IsNullOrEmpty(str))
                return 0.0M;
            switch (str.Trim().ToLower())
            {
                case "true":
                case "t":
                    return 1.0M;
            }
            string newStr = string.Empty;
            newStr = Chinese2Num(str).ToString();
            newStr = str.Trim("0123456789.+-".ToCharArray());
            str = str.Trim(newStr.ToCharArray());
            if (!decimal.TryParse(str, out result))
            {
                string NewStr = ToDBC(str);
                if (NewStr != str)
                    return StringToDecimal(NewStr);
                result = 0M;
            }
            return result;
        }
        /// <summary>
        /// 万能内容转Decimal
        /// </summary>
        /// <param name="anything">任何东西。能处理全角，中文大写数字，布尔，null，dbnull</param>
        /// <returns></returns>
        public static decimal ToDecimal(object? anything)
        {
            if (anything == null)
                return 0;
            if (anything == DBNull.Value)
                return 0;
            return StringToDecimal((string)anything);
        }

        /// <summary>
        /// 万能内容转Long
        /// </summary>
        /// <param name="anything">任何东西。能处理全角，中文大写数字，布尔，null，dbnull</param>
        /// <returns></returns>
        public static long ToLong(object anything)
        {
            if (anything == null)
                return 0;
            if (anything == DBNull.Value)
                return 0;
            return StringToLong(anything.ToString());
        }

        /// <summary>
        /// 字符串转长型。会尽量提取一般字符串中的数字，忽略非数字字符；布尔描述的true或者t会转化成1，其他字符串会转化成0。
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns>长型</returns>
        private static long StringToLong(string str)
        {
            long result =0;
            if (string.IsNullOrEmpty(str))
                return 0;
            switch (str.Trim().ToLower())
            {
                case "true":
                case "t":
                    return 0;
            }
            string newStr = string.Empty;
            newStr = Chinese2Num(str).ToString();
            newStr = str.Trim("0123456789.+-".ToCharArray());
            str = str.Trim(newStr.ToCharArray());
            if (!long.TryParse(str, out result))
            {
                string NewStr = ToDBC(str);
                if (NewStr != str)
                    return StringToLong(NewStr);
                result = 0;
            }
            return result;
        }

        /// <summary>
        /// 获取文件MD5值
        /// </summary>
        /// <param name="file">文件绝对路径</param>
        /// <returns>MD5值</returns>
        public static string GetMD5HashFromFile(string file)
        {
            try
            {
                FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
                System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
                byte[] retVal = md5.ComputeHash(fileStream);
                fileStream.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("获取文件MD5值error:" + ex.Message);
            }
        }
        public static string ConvertUnicodeToUtf8(string unicode)
        {
            if (string.IsNullOrEmpty(unicode))
            {
                return string.Empty;
            }
            return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled)
                      .Replace(unicode, p => Convert.ToChar(Convert.ToUInt16(p.Result("$1"), 16)).ToString());
        }
        public static string UTF2GB(string text)
        {
            byte[] bs = Encoding.GetEncoding("UTF-8").GetBytes(text);
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            bs = Encoding.Convert(Encoding.GetEncoding("UTF-8"), Encoding.GetEncoding("GB2312"), bs);
            return Encoding.GetEncoding("GB2312").GetString(bs);
        }

        public static string ReadItemFromConfig(DataTable dt, string itemName)
        {
            string value = string.Empty;
            try
            {
                if (dt == null)
                    return value;

                DataRow[] found = dt.Select("item = '" + itemName + "'");
                if (found != null && found.Length > 0)
                    value = ToString(found[0]["value"]);
            }
            catch (Exception ex)
            { }
            return value;
        }

        public static void SetItemFromConfig(ref DataTable dt, string itemName, string value)
        {
            try
            {
                if (dt == null && !dt.Columns.Contains("item") && !dt.Columns.Contains("value"))
                    return;

                DataRow[] found = dt.Select("item = '" + itemName + "'");
                if (found != null && found.Length > 0)
                {
                    found[0]["value"] = value;
                }
                else
                {
                    DataRow newRow = dt.NewRow();
                    newRow["item"] = itemName;
                    newRow["value"] = value;
                    dt.Rows.Add(newRow);
                }
            }
            catch (Exception ex)
            { }
        }

        public static void RunInAfterCurrentCodes(System.Windows.Controls.Control me, EventHandler RunAfterEvent)
        {
            try
            {
                System.Threading.ThreadStart ts = new ThreadStart(() => {
                    try
                    {
                        me.Dispatcher.Invoke(new Action(() => {
                            try
                            {
                                RunAfterEvent.Invoke(me, new EventArgs());
                            }
                            catch (Exception ex)
                            {

                            }
                        }));
                    }
                    catch (Exception ex)
                    { }

                
                });
                System.Threading.Thread t = new Thread(ts);
                t.IsBackground = true;
                t.Start();
            }
            catch (Exception ex)
            { }
        }
    }
    public delegate void NormalEvent<T>(T Parameter);

    public delegate void NormalRefEvent<T>(ref T Parameter);
    public delegate S NormalRetRefEvent<S, T>(ref T Parameter);
    public delegate S NormalRetRefEvent<S, T, R>(ref T Parameter, R Parameter2);
    public delegate S NormalRetRefEvent<S, T, T2, R>(ref T Parameter, T2 Parameter2, R Parameter3);
    public class Logger
    {
        public static Logger? _i;
        public static Logger Instance
        {
            get
            {
                if (_i == null)
                    _i = new Logger("", "", null, false, true);
                return _i;
            }
            set
            {
                _i = value;

            }
        }
        public string FileName { get; protected set; }
        public string Path { get; protected set; }

        protected NormalEvent<string> OtherMessageBox;

        protected void ShowMessagebox(string Message)
        {
            if (OtherMessageBox != null)
            {
                OtherMessageBox(Message);
                return;
            }
            //Helper.ShowMessage(Message, "日志提示");
            MessageBox.Show(Message, "日志提示");

        }
        public Logger(string Path, string FileName, NormalEvent<string>? MessageboxShow, bool ReplaceInstance = false, bool Quiet = false)
        {
            string ErrorMsg = string.Empty;
            OtherMessageBox = MessageboxShow;

            this.FileName = FileName;
            if (string.IsNullOrEmpty(this.FileName))
            {
                if (!string.IsNullOrEmpty(ErrorMsg))
                    ErrorMsg += "\r\n";
                ErrorMsg += "未指定日志文件名，使用默认文件名Log.txt";
                this.FileName = "Log.txt";
            }
            this.Path = Path;
            if (string.IsNullOrEmpty(this.Path))
            {
                if (!string.IsNullOrEmpty(ErrorMsg))
                    ErrorMsg += "\r\n";
                ErrorMsg += "未指定日志路径，使用默认路径:" + System.Environment.CurrentDirectory;
                this.Path = System.Environment.CurrentDirectory;
            }
            else if (!System.IO.Directory.Exists(this.Path))
            {
                if (!string.IsNullOrEmpty(ErrorMsg))
                    ErrorMsg += "\r\n";
                ErrorMsg += "未找到指定的日志路径，使用默认路径:" + System.Environment.CurrentDirectory;
                this.Path = System.Environment.CurrentDirectory;
            }
            if (ReplaceInstance)
                Instance = this;

            if (!Quiet && !string.IsNullOrEmpty(ErrorMsg))
                ShowMessagebox(ErrorMsg);
        }

        public void Log(string Information)
        {
            try {
                string s = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + Information;
                using (StreamWriter sw = new StreamWriter(Path + @"\" + FileName, true))
                {
                    sw.WriteLine(s);
                }
            } catch { }

            //// 从文件中读取并显示每行
            //string line = "";
            //using (StreamReader sr = new StreamReader("names.txt"))
            //{
            //    while ((line = sr.ReadLine()) != null)
            //    {
            //        Console.WriteLine(line);
            //    }
            //}
            //Console.ReadKey();
        }
    }
    /// <summary>
    /// 复制粘贴帮助类
    /// </summary>
    public class ClipboardHelper
    {

        /// <summary>
        /// 复制到剪切板
        /// </summary>
        /// <param name="text">文字</param> 
        public static void CopyText(string text)
        {
            Clipboard.SetText(text);
        }

        /// <summary>
        /// 复制或剪切文件到剪切板
        /// </summary>
        /// <param name="filePath">文件路径数组</param>
        /// <remarks>清空剪切板</remarks>
        public static void SetFileDrop(string filePath)
        {
            if (filePath == null) return;
            SetFileDropList(new[] { filePath });
        }
        /// <summary>
        /// 复制或剪切文件到剪切板
        /// </summary>
        /// <param name="files">文件路径数组</param>
        /// <remarks>清空剪切板</remarks>
        public static void SetFileDropList(string[] files)
        {
            Clipboard.Clear();//清空剪切板 
            StringCollection strcoll = new StringCollection();
            foreach (var file in files)
            {
                strcoll.Add(file);
            }
            Clipboard.SetFileDropList(strcoll);
        }

        /// <summary>
        /// 复制或剪切文件到剪切板
        /// </summary>
        /// <param name="filePath">文件路径数组</param>
        /// <param name="cut">true:剪切；false:复制</param>
        public static void CopyFile(string filePath, bool cut = false)
        {
            if (filePath == null) return;
            CopyFileList(new[] { filePath }, cut);
        }
        /// <summary>
        /// 复制或剪切文件到剪切板
        /// </summary>
        /// <param name="files">文件路径数组</param>
        /// <param name="cut">true:剪切；false:复制</param>
        public static void CopyFileList(string[] files, bool cut = false)
        {
            if (files == null) return;
            IDataObject data = new DataObject(DataFormats.FileDrop, files);
            MemoryStream memo = new MemoryStream(4);
            byte[] bytes = new byte[] { (byte)(cut ? 2 : 5), 0, 0, 0 };
            memo.Write(bytes, 0, bytes.Length);
            data.SetData("PreferredDropEffect", memo);
            Clipboard.SetDataObject(data, false);
        }

        /// <summary>
        /// 获取剪贴板中的文件列表（方法）
        /// </summary>
        /// <returns>System.Collections.List<string>返回剪切板中文件路径集合</returns>
        public static List<string> GetClipboardList()
        {
            List<string> clipboardList = new List<string>();
            StringCollection sc = Clipboard.GetFileDropList();
            foreach (var listFileName in sc)
            {
                clipboardList.Add(listFileName);
            }
            return clipboardList;
        }
    }
}
